<template>
  <div class="app-container">
    <!-- 工艺路线查询区域 -->
    <el-form :model="routeQueryParams" ref="routeQueryRef" :inline="true" v-show="showSearch" label-width="120px">
      <el-form-item label="工艺路线编号" prop="routeCode">
        <el-input v-model="routeQueryParams.routeCode" placeholder="请输入工艺路线编号" clearable @keyup.enter="getRouteList" />
      </el-form-item>
      <el-form-item label="工艺路线名称" prop="routeName">
        <el-input v-model="routeQueryParams.routeName" placeholder="请输入工艺路线名称" clearable @keyup.enter="getRouteList" />
      </el-form-item>
      <el-form-item label="是否启用" prop="enableFlag">
        <el-select v-model="routeQueryParams.enableFlag" placeholder="请选择是否启用" clearable @change="getRouteList">
          <el-option label="是" value="是"></el-option>
          <el-option label="否" value="否"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="getRouteList">搜索</el-button>
        <el-button icon="Refresh" @click="resetRouteQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 工艺路线操作按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleRouteAdd" v-hasPermi="['route:route:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="routeSingle" @click="handleRouteUpdate" v-hasPermi="['route:route:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="routeMultiple" @click="handleRouteDelete" v-hasPermi="['route:route:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleRouteExport" v-hasPermi="['route:route:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getRouteList"></right-toolbar>
    </el-row>

    <!-- 工艺路线表格 -->
    <el-table v-loading="routeLoading" :data="routeList" @selection-change="handleRouteSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="工艺路线ID" align="center" prop="routeId" /> -->
      <el-table-column label="工艺路线编号" align="center" prop="routeCode" />
      <el-table-column label="工艺路线名称" align="center" prop="routeName" />
      <el-table-column label="是否启用" align="center" prop="enableFlag">
        <template #default="scope">
          <el-tag :type="scope.row.enableFlag === '是' ? 'success' : 'info'">{{ scope.row.enableFlag }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleRouteUpdate(scope.row)" v-hasPermi="['route:route:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleRouteDelete(scope.row)" v-hasPermi="['route:route:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 工艺路线分页 -->
    <pagination v-show="routeTotal>0" :total="routeTotal" v-model:page="routeQueryParams.pageNum" v-model:limit="routeQueryParams.pageSize" @pagination="getRouteList" />

    <!-- 工艺路线弹窗（管理主数据） -->
    <el-dialog :title="routeTitle" v-model="routeOpen" width="900px" append-to-body>
      <el-form ref="routeFormRef" :model="routeForm" :rules="routeRules" label-width="80px">
        <!-- 编号 + 自动生成开关 -->
        <el-form-item label="工艺路线编号" prop="routeCode">
          <el-input v-model="routeForm.routeCode" placeholder="请输入工艺路线编号" clearable :disabled="routeForm.autoGenerate" :readonly="routeForm.autoGenerate" />
          <el-switch v-model="routeForm.autoGenerate" style="margin-left: 10px;" @change="handleRouteAutoGenerateChange" />
          <span style="margin-left: 5px;">自动生成</span>
          <el-loading v-if="generatingRouteCode" text="正在生成编号..." size="small" style="margin-left: 10px;" />
        </el-form-item>

        <!-- 名称 -->
        <el-form-item label="工艺路线名称" prop="routeName">
          <el-input v-model="routeForm.routeName" placeholder="请输入工艺路线名称" clearable />
        </el-form-item>

        <!-- 是否启用（单选组） -->
        <el-form-item label="是否启用" prop="enableFlag">
          <el-radio-group v-model="routeForm.enableFlag">
            <el-radio label="是">是</el-radio>
            <el-radio label="否">否</el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- 说明（文本域） -->
        <el-form-item label="说明" prop="routeDesc">
          <el-input v-model="routeForm.routeDesc" type="textarea" placeholder="请输入内容" :autosize="{minRows: 3, maxRows: 3}" />
        </el-form-item>

        <!-- 备注（文本域） -->
        <el-form-item label="备注" prop="remark">
          <el-input v-model="routeForm.remark" type="textarea" placeholder="请输入内容" :autosize="{minRows: 3, maxRows: 3}" />
        </el-form-item>
      </el-form>

      <!-- Tabs 区域：组成工序 + 关联产品 -->
       <!-- Tabs 区域：仅在修改时显示（routeId存在） -->
      <div v-if="routeForm.routeId" style="margin-top: 20px;">
        <el-tabs type="border-card">
          <!-- 组成工序标签页 -->
          <el-tab-pane label="组成工序">
            <!-- 工艺组成查询表单 -->
            <el-form :model="routeprocessQueryParams" ref="routeprocessQueryRef" :inline="true" label-width="68px">
              <el-form-item>
                <el-button type="primary" icon="Search" @click="getRouteprocessList(routeForm.routeId)">搜索</el-button>
                <el-button icon="Refresh" @click="resetRouteprocessQuery">重置</el-button>
              </el-form-item>
            </el-form>

            <!-- 工艺组成操作按钮 -->
            <el-row :gutter="10" class="mb8">
              <el-col :span="1.5">
                <el-button type="primary" plain icon="Plus" @click="handleRouteprocessAdd" v-hasPermi="['routeprocess:routeprocess:add']">新增</el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button type="success" plain icon="Edit" :disabled="routeprocessSingle" @click="handleRouteprocessUpdate" v-hasPermi="['routeprocess:routeprocess:edit']">修改</el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button type="danger" plain icon="Delete" :disabled="routeprocessMultiple" @click="handleRouteprocessDeleteBatch" v-hasPermi="['routeprocess:routeprocess:remove']">删除</el-button>
              </el-col>
            </el-row>

            <!-- 工艺组成表格 -->
            <el-table v-loading="routeprocessLoading"  :data="sortedRouteprocessList"  @selection-change="handleRouteprocessSelectionChange">
              <el-table-column type="selection" width="55" align="center" />
              <!-- <el-table-column label="记录ID" align="center" prop="recordId" /> -->
              <el-table-column label="工序编码" align="center" prop="processCode" />
              <el-table-column label="工序名称" align="center" prop="processName" />
              <el-table-column label="序号" align="center" prop="orderNum" />
              <el-table-column label="与下一道工序关系" align="center" prop="linkType" />
              <el-table-column label="甘特图显示颜色" align="center" prop="colorCode">
                <template #default="scope">
                  <div :style="{ backgroundColor: scope.row.colorCode, width: '20px', height: '20px', display: 'inline-block' }"></div>
                  {{ scope.row.colorCode }}
                </template>
              </el-table-column>
              <el-table-column label="关键工序" align="center" prop="keyFlag" />
              <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template #default="scope">
                  <el-button link type="primary" icon="Edit" @click="handleRouteprocessUpdate(scope.row)" v-hasPermi="['routeprocess:routeprocess:edit']">修改</el-button>
                  <el-button link type="primary" icon="Delete" @click="handleRouteprocessDelete(scope.row)" v-hasPermi="['routeprocess:routeprocess:remove']">删除</el-button>
                </template>
              </el-table-column>
            </el-table>

            <!-- 工艺组成分页 -->
            <pagination v-show="routeprocessTotal>0" :total="routeprocessTotal" v-model:page="routeprocessQueryParams.pageDto.current" v-model:limit="routeprocessQueryParams.pageDto.size" @pagination="getRouteprocessList(routeForm.routeId)" />

            <!-- 工艺组成弹窗（管理工序关联） -->
            <el-dialog :title="routeprocessTitle" v-model="routeprocessOpen" width="700px" append-to-body>
              <el-form ref="routeprocessFormRef" :model="routeprocessForm" :rules="routeprocessRules" size="default" label-width="100px">
                <el-row gutter="15">
                  <el-col :span="12">
                    <el-form-item label="序号" prop="orderNum">
                      <el-input-number v-model="routeprocessForm.orderNum" placeholder="1"></el-input-number>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="工序" prop="processName">
                      <el-select v-model="routeprocessForm.processId"  @change="handleProcessChange" placeholder="请选择工序" clearable :style="{width: '100%'}">
                        <el-option v-for="(item, index) in processCodeOptions" :key="index" :label="item.processName" :value="item.processId" :disabled="item.disabled"></el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row gutter="15">
                  <el-col :span="12">
                    <el-form-item label-width="140px" label="与下一道工序关系" prop="linkType">
                      <el-select v-model="routeprocessForm.linkType" placeholder="请选择与下一道工序关系" clearable :style="{width: '100%'}">
                        <el-option v-for="(item, index) in linkTypeOptions" :key="index" :label="item.label" :value="item.value" :disabled="item.disabled"></el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="10">
                    <el-form-item label-width="120px" label="甘特图显示颜色" prop="colorCode">
                      <el-color-picker v-model="routeprocessForm.colorCode" show-alpha placeholder="请选择甘特图显示颜色" :predefine="predefineColors" />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row gutter="15">
                  <el-col :span="11">
                    <el-form-item label-width="110px" label="是否关键工序" prop="keyFlag">
                      <el-select v-model="routeprocessForm.keyFlag" placeholder="请选择" clearable :style="{width: '100%'}">
                        <el-option v-for="(item, index) in keyFlagOptions" :key="index" :label="item.label" :value="item.value" :disabled="item.disabled"></el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="11">
                    <el-form-item label-width="140px" label="是否需要质检确认" prop="isCheck">
                      <el-select v-model="routeprocessForm.isCheck" placeholder="请选择" clearable :style="{width: '100%'}">
                        <el-option v-for="(item, index) in isCheckOptions" :key="index" :label="item.label" :value="item.value" :disabled="item.disabled"></el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row gutter="15">
                  <el-col :span="10">
                    <el-form-item label="准备时间" prop="defaultPreTime">
                      <el-input-number v-model="routeprocessForm.defaultPreTime" placeholder="0"></el-input-number>
                    </el-form-item>
                  </el-col>
                  <el-col :span="10">
                    <el-form-item label="等待时间" prop="defaultSufTime">
                      <el-input-number v-model="routeprocessForm.defaultSufTime" placeholder="0"></el-input-number>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row gutter="15">
                  <el-col :span="24">
                    <el-form-item label="备注" prop="remark">
                      <el-input v-model="routeprocessForm.remark" type="textarea" placeholder="请输入内容" :autosize="{minRows: 4, maxRows: 4}" :style="{width: '100%'}" />
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form>
              <template #footer>
                <div class="dialog-footer">
                  <el-button type="primary" @click="submitRouteprocessForm">确 定</el-button>
                  <el-button @click="routeprocessOpen = false">取 消</el-button>
                </div>
              </template>
            </el-dialog>
          </el-tab-pane>
      <!-- 关联产品标签页 -->
      <el-tab-pane label="关联产品">
    <!-- 关键：通过 props 传递 routeId -->
       <RouteProduct :current-route-id="routeForm.routeId" />
      </el-tab-pane>
      </el-tabs>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitRouteForm">确 定</el-button>
          <el-button @click="routeOpen = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Route">
import { listRoute, getRoute, delRoute, addRoute, updateRoute } from "@/api/route/route";
import { listRouteprocess, getRouteprocess, delRouteprocess, addRouteprocess, updateRouteprocess } from "@/api/routeprocess/routeprocess";
import { listProcess } from "@/api/workstation/workstation";
import { getCurrentInstance, reactive, ref, toRefs } from 'vue';
import Pagination from '@/components/Pagination';
import RightToolbar from '@/components/RightToolbar';
// 关键：引入 RouteProduct 组件（路径需根据实际文件位置调整）
import RouteProduct from '@/views/routeproduct/routeproduct/index.vue'; 

const { proxy } = getCurrentInstance();

// ========== 工艺路线 响应式数据 ==========
const routeList = ref([]);
const routeOpen = ref(false); // 工艺路线弹窗显隐
const routeTitle = ref("");  // 工艺路线弹窗标题
const routeForm = ref({
  routeId: null,
  routeCode: '',
  routeName: '',
  enableFlag: '是',
  autoGenerate: false,
  routeDesc: '',
  remark: '',
  attr1: null,
  attr2: null,
});
const generatingRouteCode = ref(false); // 工艺路线编号生成加载
const routeQueryParams = ref({
  pageNum: 1,
  pageSize: 10,
  routeCode: null,
  routeName: null,
  enableFlag: null,
});
const routeRules = ref({
  routeCode: [{ required: true, message: "工艺路线编号不能为空", trigger: ["blur", "change"] }],
  routeName: [{ required: true, message: "工艺路线名称不能为空", trigger: "blur" }],
  enableFlag: [{ required: true, message: "是否启用不能为空", trigger: "change" }],
});
const routeIds = ref([]);
const routeSingle = ref(true);
const routeMultiple = ref(true);
const routeTotal = ref(0);
const showSearch = ref(true);
const routeLoading = ref(true);

// ========== 工艺组成 响应式数据 ==========
import { computed } from 'vue'
const routeprocessList = ref([]);
const routeprocessOpen = ref(false); // 工艺组成弹窗显隐
const routeprocessTitle = ref("");  // 工艺组成弹窗标题
const routeprocessForm = ref({
  recordId: null,
  routeId: null, // 关联工艺路线ID
  processName: null,
  orderNum: 1,
  linkType: null,
  defaultPreTime: 0,
  defaultSufTime: 0,
  colorCode: '#00AEF3',
  keyFlag: null,
  isCheck: null,
  remark: null,
});
const processCodeOptions = ref([]);
const linkTypeOptions = ref([
  { label: "连续", value: "CONTINUOUS" },
  { label: "并行", value: "PARALLEL" },
  { label: "等待", value: "WAIT" }
]);
const keyFlagOptions = ref([
  { label: "是", value: "Y" },
  { label: "否", value: "N" }
]);
const isCheckOptions = ref([
  { label: "是", value: "Y" },
  { label: "否", value: "N" }
]);
const predefineColors = ref([
  '#ff4500', '#ff8c00', '#ffd700', '#90ee90', 
  '#00ced1', '#1e90ff', '#c71585', '#808080'
]);
const routeprocessIds = ref([]);
const routeprocessSingle = ref(true);
const routeprocessMultiple = ref(true);
const routeprocessTotal = ref(0);
const routeprocessQueryParams = ref({
  pageDto: { current: 1, size: 10 },
});
const routeprocessRules = ref({
  processId: [{ required: true, message: "工序不能为空", trigger: "blur" }],
  keyFlag: [{ required: true, message: "是否关键工序不能为空", trigger: "change" }],
  isCheck: [{ required: true, message: "是否需要质检确认不能为空", trigger: "change" }],
});
const routeprocessLoading = ref(true);
// 计算属性：按 orderNum 升序排序（处理类型+空值）
const sortedRouteprocessList = computed(() => {
  return [...routeprocessList.value].sort((a, b) => {
    // 将 orderNum 转为数字，空值/非数字则视为 0
    const numA = Number(a.orderNum) || 0;
    const numB = Number(b.orderNum) || 0;
    return numA - numB; // 升序排列
  });
});
// ========== 关联产品 响应式数据 ==========
// ========== 工艺路线 方法 ==========
// 查询工艺路线列表
function getRouteList() {
  routeLoading.value = true;
  listRoute(routeQueryParams.value).then(response => {
    routeList.value = response.rows;
    routeTotal.value = response.total;
    routeLoading.value = false;
  }).catch(() => {
    routeLoading.value = false;
  });
}

// 重置工艺路线查询
function resetRouteQuery() {
  if (proxy && proxy.resetForm) {
    proxy.resetForm("routeQueryRef");
  }
  routeQueryParams.value = {
    pageNum: 1,
    pageSize: 10,
    routeCode: null,
    routeName: null,
    enableFlag: null,
  };
  getRouteList();
}

// 工艺路线多选事件
function handleRouteSelectionChange(selection) {
  routeIds.value = selection.map(item => item.routeId);
  routeSingle.value = selection.length !== 1;
  routeMultiple.value = !selection.length;
}

// 添加工艺路线
function handleRouteAdd() {
  routeForm.value = {
    routeId: null,
    route_id: routeForm.value.routeId, // 关联当前工艺路线ID
    routeCode: '',
    routeName: '',
    enableFlag: '是',
    autoGenerate: false,
    routeDesc: '',
    remark: '',
  };
  routeOpen.value = true;
  routeTitle.value = "添加工艺路线";
  // 新增时工艺组成无数据，直接置空并结束加载
  routeprocessList.value = [];
  routeprocessTotal.value = 0;
  routeprocessLoading.value = false; 
}

// 修改工艺路线
function handleRouteUpdate(row) {
  const _routeId = row ? row.routeId : (routeIds.value.length > 0 ? routeIds.value[0] : null);
  if (!_routeId) {
    proxy.$modal.msgWarning('请选择一条记录进行修改');
    return;
  }
  getRoute(_routeId).then(response => {
    routeForm.value = { ...response.data };
    if (!routeForm.value.enableFlag) {
      routeForm.value.enableFlag = '是';
    }
    routeForm.value.autoGenerate = false;
    routeOpen.value = true;
    routeTitle.value = "修改工艺路线";
    // 关键：加载当前工艺路线的工艺组成
    getRouteprocessList(routeForm.value.routeId); 
  }).catch(error => {
    console.error('获取工艺路线详情失败', error);
    proxy.$modal.msgError('获取数据失败，请重试');
  });
}

// 工艺路线编号自动生成
function handleRouteAutoGenerateChange(checked) {
  if (checked) {
    routeForm.value.routeCode = '';
    generateRouteCode();
  }
}

// 生成工艺路线编号（前端模拟）
function generateRouteCode() {
  if (!routeForm.value.autoGenerate) return;
  generatingRouteCode.value = true;
  setTimeout(() => {
    try {
      const prefix = 'ROUTE-';
      const date = new Date();
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, '0');
      const day = date.getDate().toString().padStart(2, '0');
      const dateStr = `${year}${month}${day}`;
      const random = Math.floor(Math.random() * 1000).toString().padStart(3, '0');
      routeForm.value.routeCode = `${prefix}${dateStr}-${random}`;
    } catch (error) {
      console.error('生成编号异常', error);
      proxy.$modal.msgWarning('编号生成异常，请重试');
    } finally {
      generatingRouteCode.value = false;
    }
  }, 300);
}

// 提交工艺路线表单
function submitRouteForm() {
  const routeFormRef = proxy.$refs["routeFormRef"];
  if (!routeFormRef) return;
  routeFormRef.validate(valid => {
    if (valid) {
      if (routeForm.value.autoGenerate && !routeForm.value.routeCode) {
        generateRouteCode();
        setTimeout(() => {
          routeFormRef.validate(innerValid => {
            if (innerValid) {
              performRouteSubmit();
            }
          });
        }, 350);
        return;
      }
      performRouteSubmit();
    }
  });
}

// 执行工艺路线提交
function performRouteSubmit() {
  const submitFn = routeForm.value.routeId ? updateRoute : addRoute;
  submitFn(routeForm.value).then(() => {
    proxy.$modal.msgSuccess(routeForm.value.routeId ? "修改成功" : "新增成功");
    routeOpen.value = false;
    getRouteList();
  }).catch(error => {
    console.error(routeForm.value.routeId ? '修改失败' : '新增失败', error);
    proxy.$modal.msgError(error.msg || '操作失败，请重试');
  });
}

// 删除工艺路线
function handleRouteDelete(row) {
  const _routeIds = row ? [row.routeId] : routeIds.value;
  if (_routeIds.length === 0) {
    proxy.$modal.msgWarning('请选择需要删除的记录');
    return;
  }
  proxy.$modal.confirm(`是否确认删除选中的${_routeIds.length}条工艺路线数据？`).then(() => {
    delRoute(_routeIds).then(() => {
      getRouteList();
      proxy.$modal.msgSuccess("删除成功");
    }).catch(() => {});
  });
}

// 导出工艺路线
function handleRouteExport() {
  proxy.download('route/route/export', { ...routeQueryParams.value }, `route_${new Date().getTime()}.xlsx`);
}

// ========== 工艺组成 方法 ==========
// 查询工艺组成列表（关联工艺路线ID）
function getRouteprocessList(routeId) {
  if (!routeId) return; // 工艺路线ID为空时不查询
  routeprocessQueryParams.value.routeId = routeId;
  routeprocessLoading.value = true;
  listRouteprocess(routeprocessQueryParams.value).then(res => {
    routeprocessList.value = res.data.records;
    routeprocessTotal.value = res.data.pageDto.total;
    routeprocessLoading.value = false;
  });
}

// 重置工艺组成查询
function resetRouteprocessQuery() {
  routeprocessQueryParams.value = {
    pageDto: { current: 1, size: 10 },
  };
  getRouteprocessList(routeForm.value.routeId);
}

// 工艺组成多选事件
function handleRouteprocessSelectionChange(selection) {
  routeprocessIds.value = selection.map(item => item.recordId);
  routeprocessSingle.value = selection.length !== 1;
  routeprocessMultiple.value = !selection.length;
}

// 添加工艺组成
function handleRouteprocessAdd() {
  routeprocessForm.value = {
    recordId: null,
    routeId: routeForm.value.routeId, // 关联当前工艺路线ID
    processId: null, // 新增processId字段
    processCode: '',  // 新增：工序编码
    processName: '',  // 新增：工序名称
    orderNum: 1,
    defaultPreTime: 0,
    defaultSufTime: 0,
    colorCode: '#00AEF3',
    keyFlag: null,
    isCheck: null,
    remark: null,
  };
  listProcess().then(res => {
   console.log("工序列表数据：", res.data); 
    processCodeOptions.value = res.data;
  });
  routeprocessOpen.value = true;
  routeprocessTitle.value = "添加工艺组成";
}

// 修改工艺组成
function handleRouteprocessUpdate(row) {
  routeprocessForm.value = { ...row };
  listProcess().then(res => {
    processCodeOptions.value = res.data;
  });
  routeprocessOpen.value = true;
  routeprocessTitle.value = "修改工艺组成";
}

// 提交工艺组成表单
function submitRouteprocessForm() {
  const routeprocessFormRef = proxy.$refs["routeprocessFormRef"];
  if (routeprocessFormRef) {
    routeprocessFormRef.validate(valid => {
      if (valid) {
        console.log("提交的工艺组成数据：", routeprocessForm.value); 
        const submitFn = routeprocessForm.value.recordId ? updateRouteprocess : addRouteprocess;
        submitFn(routeprocessForm.value).then(() => {
          proxy.$modal.msgSuccess(routeprocessForm.value.recordId ? "修改成功" : "新增成功");
          routeprocessOpen.value = false;
          getRouteprocessList(routeForm.value.routeId); // 刷新工艺组成列表
        });
      }
    });
  }
}

// 单条删除工艺组成
function handleRouteprocessDelete(row) {
  const _recordId = row.recordId;
  proxy.$modal.confirm('是否确认删除该工艺组成？').then(() => {
    delRouteprocess(_recordId).then(() => {
      getRouteprocessList(routeForm.value.routeId);
      proxy.$modal.msgSuccess("删除成功");
    });
  });
}

// 批量删除工艺组成
function handleRouteprocessDeleteBatch() {
  if (routeprocessIds.value.length === 0) {
    proxy.$modal.msgWarning("请选择要删除的工艺组成");
    return;
  }
  proxy.$modal.confirm('是否确认删除选中的工艺组成？').then(() => {
    delRouteprocess(routeprocessIds.value).then(() => {
      getRouteprocessList(routeForm.value.routeId);
      routeprocessIds.value = [];
      routeprocessSingle.value = true;
      routeprocessMultiple.value = true;
      proxy.$modal.msgSuccess("删除成功");
    });
  });
}
// 选择工序后，同步processCode和processName
function handleProcessChange(processId) {
  // 根据选中的processId，从工序列表中找到对应的工序
  const selectedProcess = processCodeOptions.value.find(item => item.processId === processId);
  if (selectedProcess) {
    // 同步工序编码和名称到表单
    routeprocessForm.value.processCode = selectedProcess.processCode; 
    routeprocessForm.value.processName = selectedProcess.processName; 
  } else {
    // 未选中时清空
    routeprocessForm.value.processCode = '';
    routeprocessForm.value.processName = '';
  }
}

// 初始化加载工艺路线列表
getRouteList();
</script>

<style scoped>
.dialog-footer {
  text-align: right;
}
</style>